package com.hrt.common.db;

import com.btcode.db.result.Row;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 树状数据结构工具类
 *
 * @author gislin
 */
public class TreeDataUtil {

    private static String parentIdKey = "PARENT_ID";

    /**
     * 循环构造树
     */
    public static List<Row> buildTrees(List<Row> models) {
        List<Row> bosss = findBoss(models);
        bosss.forEach(parentModel -> buildTreeSingle(models, parentModel));
        return bosss;
    }

    /**
     * 拿到一个父节点后，递归获取其下面的子节点，效率待优化
     */
    private static void buildTreeSingle(List<Row> models, Row parendModel) {

        List<Row> childs = findChild(models, parendModel);
        if (childs.size() > 0) {
            parendModel.put("children", childs);
            childs.stream().forEach(child -> {
                buildTreeSingle(models, child);
            });
        }
    }

    /**
     * 获取父节点集合
     */
    private static List<Row> findBoss(List<Row> models) {
        List<Row> bosss = models.stream().filter(model -> model.get(parentIdKey) == null).collect(
            Collectors.toList());
        return bosss;
    }

    /**
     * 获取指定父节点的下一级子节点
     */
    private static List<Row> findChild(List<Row> models, Row parendModel) {

        Object id = parendModel.get("ID");

        List<Row> child = new ArrayList<>();

        if (id == null) {
            return child;
        }

        child = models.stream().filter(model -> {
            Object parentid = model.get(parentIdKey);
            return id.equals(parentid);
        }).collect(Collectors.toList());

        return child;
    }
}
